package com.yourcom.proname.biz.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yourcom.proname.vo.CommonResVo;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * ip黑名单
 */
@WebFilter
public class IPFilter extends OncePerRequestFilter {

    private List<String> forbiddenIpList = new ArrayList<>();

    public IPFilter() {
        this.forbiddenIpList.add("10.112.13.167");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String ip = request.getRemoteAddr();
        if (this.forbiddenIpList.contains(ip)) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ObjectMapper objectMapper = new ObjectMapper();
            out.write(objectMapper.writeValueAsString(CommonResVo.fail(400, "禁止访问的ip")));
            out.flush();
        } else {
            filterChain.doFilter(request, response);
            System.out.println(response);
        }
    }
}
